package org.ponly.fs.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import org.ponly.fs.FileSystemException;
import org.ponly.fs.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 基于阿里云 OSS 的文件系统实现
 * <p/>
 * 1. 开通 OSS <br/>
 * 2. 创建 bucket <br/>
 * 3. 为 bucket 绑定域名, eg:  <br/>
 *
 * @author tianxuan
 */
public class AliyunOss implements OssFileSystem {
    private static final Logger LOG = LoggerFactory.getLogger(AliyunOss.class);

    private final String endpoint; //访问OSS的域名
    private final String accessKeyId;
    private final String secretAccessKey;
    private final String bucketName; //Bucket用来管理所存储Object的存储空间

    public AliyunOss(String endpoint, String accessKeyId, String secretAccessKey, String bucketName) {
        this.endpoint = "https://" + endpoint;
        this.accessKeyId = accessKeyId;
        this.secretAccessKey = secretAccessKey;
        this.bucketName = bucketName;
        initBucketName();
    }

    @Override
    public InputStream open(String file)  {
        InputStream in = null;
        try {
            in = new FileInputStream(this.getFile(file));
        } catch (Exception e) {
            LOG.debug("获取OSS资源失败: {}", bucketName);
        }
        return in;
    }

    @Override
    public File getFile(String file) throws FileSystemException {
        File f = null;
        OSSClient ossClient = getOSSClient();
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        try {
            File tempFile = File.createTempFile("ponly-ils", FileUtil.getExtension(file, true));
            ossClient.getObject(new GetObjectRequest(bucketName, file), tempFile);
            f = tempFile;
        } catch (Exception e) {
            LOG.debug("获取OSS资源失败: {}", bucketName);
        }finally {
            ossClient.shutdown();
        }
        return f;
    }

    @Override
    public void flow(String file, InputStream in, boolean override)  {
        OSSClient ossClient = getOSSClient();
        ossClient.putObject(this.bucketName, file, in);
        ossClient.shutdown();

    }
    /**
     *
     * @Title: getOSSClient
     * @Description: 获取oss客户端
     * @return OSSClient oss客户端
     * @throws
     */
    private OSSClient getOSSClient() {
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, secretAccessKey);
        return ossClient;
    }

    /**
     * 初始化OssbucketName
     */
    private void initBucketName(){
        OSSClient ossClient = getOSSClient();
        if (ossClient.doesBucketExist(bucketName)) {
            LOG.debug("Bucket存在: {}", bucketName);
        } else {
            LOG.debug("Bucket不存在，即将创建: {}", bucketName);
            ossClient.createBucket(bucketName);
        }
        ossClient.shutdown();
    }
}
